import { Component, OnInit, Inject, ViewChild, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgForm, FormControl } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDatepickerInputEvent} from '@angular/material';
import { Moment } from 'moment';
import * as moment from 'moment';
declare var $: any;
import { Asset} from '../../models/Asset';
import { User } from '../../models/User';
import { Department } from '../../models/Department';
import { UserService } from '../../service/userService';
import { AssetService } from '../../service/assetService';
import { DepartmentService } from '../../service/departmentService';
import { DepartmentaddComponent } from '../departmentadd/departmentadd';
import { UseraddComponent } from '../useradd/useradd';
import { AssettypeaddComponent } from '../assettypeadd/assettypeadd';
import { AssetType } from '../../models/AssetType';
import { ITreeOptions, TreeComponent } from 'angular-tree-component';
import { TREE_ACTIONS, IActionMapping } from 'angular-tree-component';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { FileUploader } from 'ng2-file-upload/ng2-file-upload';


@Component({
  templateUrl: './assetadd.html',
  styleUrls: ['./assetadd.css']
})
export class AssetaddComponent implements OnInit, AfterViewChecked {
  uploader: FileUploader = new FileUploader({
    url: environment.apiUrl + 'api/fileupload/img',
    removeAfterUpload: true,
    method: 'POST'
  });
  messages = {
    assetDepartmentId: '',
    assetCode: '',
    assetName: '',
    assetBrand: '',
    assetType: '',
    brand: '',
    source: '',
    assetVersion: '',
    sourceComefrom: '',
    assetPrice: '',
    snNum: '',
    invoiceNum: '',
    assettypeName: '',
    address: '',
    seatNum: ''
  };
  // nodes: AssetType[] = [];
  options: ITreeOptions = {};
  nodes: any = [];
  assettypeName: string;
  typetree: boolean = false;
  @ViewChild(TreeComponent)
  private tree: TreeComponent;
  beginCtrl = new FormControl();
  asset: Asset;
  departments: Department[];
  environment = environment;
  users: User[];
  assetTypes: AssetType[];
  departmentid: number;
  baseurl: string = 'http://file.sxycy.cn:8081';
  showchoose: boolean;
  imgadd: string[] = [];
  showadd: boolean = false;
  updateassets: any;
  assets: any = [];
  actionMapping: IActionMapping = {
    mouse: {
      click: (tree, node, $event) => {
        this.asset.assetType = node.data.GDZCLB_DM;
        if (this.asset.oaAssetType) {
          this.asset.oaAssetType.GDZCLBMC = node.data.GDZCLBMC;
        }
        this.assettypeName = node.data.GDZCLBMC;
        this.typetree = false;
      }
    }
  };
  constructor(
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private dialogRef: MatDialogRef<AssetaddComponent>,
    private userService: UserService,
    private assetService: AssetService,
    private departmentService: DepartmentService,
    @Inject(MAT_DIALOG_DATA) public data: {asset: Asset, assetTypes: AssetType[], assets: any}) {
    this.asset = data.asset || new Asset();
    this.updateassets = data.assets || false;
    if (!this.asset.oaAssetType) {
      this.showchoose = false;
    } else {
      this.showchoose = true;
    }
    this.asset.buyDateShow = new FormControl(moment(this.asset.buyDate));
    this.asset.buyDate = moment(this.asset.buyDate).toDate();
    this.asset.createDateShow = new FormControl(moment(this.asset.createDate));
    this.asset.createDate = moment(this.asset.createDate).toDate();
  }
  @ViewChild('assetForm')
  assetForm: NgForm;

  ngAfterViewChecked() {
    if (this.assetForm) {
      this.assetForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }
  ngOnInit() {
    console.log(this.asset);
    if (this.asset.assetImgUrl1) {
      this.imgadd.push(this.asset.assetImgUrl1);
    } if (this.asset.assetImgUrl2) {
      this.imgadd.push(this.asset.assetImgUrl2);
    }if (this.asset.assetImgUrl3) {
      this.imgadd.push(this.asset.assetImgUrl3);
    } if (!this.asset.assetImgUrl1 && !this.asset.assetImgUrl2 && !this.asset.assetImgUrl3) {
      this.imgadd = [];
    }
    this.assetService.getAssetTypes().subscribe((res) => {
      this.assetTypes = res.res;
      for (let i = 0; i < this.assetTypes.length; i++) {
        this.nodes.push({GDZCLBMC: this.assetTypes[i].GDZCLBMC, GDZCLB_DM: this.assetTypes[i].GDZCLB_DM});
      }
      this.nodes.forEach((node, index) => {
        node.children = this.assetTypes[index].children;
      })
    })
    this.getDepartments();
    // this.asset.oaAssetType = new AssetType();


    this.options = {displayField: 'GDZCLBMC', idField: 'GDZCLB_DM', actionMapping: this.actionMapping };
  }

  changeDepartment(departmentId) {
    this.departmentid = departmentId;
    this.getUsers();
  }
  getUsers() {
    this.userService.getUsers(1, 5, this.departmentid).subscribe((res) => {
      this.users = res.res;
    })
  }
  onSubmit() {
    this.checkValidate(true);
    if (this.assetForm.invalid) {
      // 触发mat的error
      this.assetForm.onSubmit(null);
      return false;
    }
    if (this.imgadd[0]) {
      this.asset.assetImgUrl1 = this.imgadd[0];
    } else  {
      this.asset.assetImgUrl1 = '';
    }
    if (this.imgadd[1]) {
      this.asset.assetImgUrl2 = this.imgadd[1];
    } else {
      this.asset.assetImgUrl2 = '';
    }
    if (this.imgadd[2]) {
      this.asset.assetImgUrl3 = this.imgadd[2];
    } else {
      this.asset.assetImgUrl3 = '';
    }

    this.asset.assetDepartmentId = Number(this.asset.assetDepartmentId);
    this.asset.assetUserId = Number(this.asset.assetUserId);
    this.asset.assetPrice = Number(this.asset.assetPrice);
    if (!this.updateassets) {
      if (this.asset.id !== undefined) {
        this.assetService.update(this.asset).subscribe((res) => {
          this.dialogRef.close(res.res);
        });
      } else {
        this.assetService.create(this.asset).subscribe((res) => {
          this.dialogRef.close(res.res);
        });
      }
    } else {
      this.updateassets.assetinfos.forEach((value) => {
        this.assets.push({id: value.id, assetName: this.asset.assetName, assetType: this.asset.assetType,
          invoiceNum: this.asset.invoiceNum, assetPrice: this.asset.assetPrice, assetNum: this.asset.assetNum, assetBrand: this.asset.assetBrand,
          source: this.asset.source, assetVersion: this.asset.assetVersion, sourceComefrom: this.asset.sourceComefrom, snNum: this.asset.snNum,
          remark: this.asset.remark, buyDate: this.asset.buyDate, createDate: this.asset.createDate, assetImgUrl1: this.asset.assetImgUrl1,
        assetImgUrl2: this.asset.assetImgUrl2, assetImgUrl3: this.asset.assetImgUrl3, seatNum: this.asset.seatNum, address: this.asset.address})
      })
      this.assetService.updatebatch(this.assets).subscribe((res) => {
        this.dialogRef.close(res);
      })
    }
  }
  onSelectbuyDate(event: MatDatepickerInputEvent<Moment>) {
    this.asset.buyDate = event.value.toDate();
    this.asset.buyDateShow = new FormControl(event.value);
  }
  onSelectcreateDate(event: MatDatepickerInputEvent<Moment>) {
    this.asset.createDate = event.value.toDate();
    this.asset.createDateShow = new FormControl(event.value);
  }

  getDepartments() {
    this.departmentService.getAllDepartments().subscribe((res) => {
      this.departments = res.res;
    })
  }


  addAssetType() {
    const dialogRef = this.dialog.open(AssettypeaddComponent, {
      width: '500px',
      height: '300px',
      data: {
        assetTypes: this.assetTypes,
        nodes: this.nodes,
      }
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.assetService.getAssetTypes().subscribe((res) => {
        this.assetTypes = res.res;
      })
    });
  }

  ImgsOnChanged(event: any) {
    this.uploader.queue.forEach(queue => {
      queue.withCredentials = false;
      queue.onError = (response: string, status: number) => {
        console.log(response, status);
      };

      queue.onSuccess = (responses, status, headers) => {
        if (status === 200) {
          const response = JSON.parse(responses);
          this.imgadd.push(response['url']);
          if (this.imgadd.length < 3) {
            this.showadd = false;
          } else {
            this.showadd = true;
          }
        } else {
          console.log('err', Error);
        }
      };
      queue.upload();
    });
  }

  deleteImg(i) {
    this.imgadd.splice(i, 1);
    this.showadd = false;
  }

  showtypeTree() {
    this.typetree = !this.typetree;
  }
  hidetree() {
    this.typetree = false;
  }

  checkValidate(isSubmit?: boolean) {
    const form = this.assetForm;

    for (const field in AssetaddComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = AssetaddComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }
    }
  }
  static ErrorMessages = {
    assetDepartmentId: {
      required: '使用部门不能为空'
    },
    assetCode: {
      required: '设备编号不能为空'
    },
    assetName: {
      required: '资产名称不能为空'
    },
    assetBrand: {
      required: '设备品牌不能为空'
    },
    assetType: {
      required: '资产类别不能为空'
    },
    source: {
      required: '设备来源不能为空'
    },
    assetVersion: {
      required: '设备版本不能为空'
    },
    sourceComefrom: {
      required: '设备渠道不能为空'
    },
    assetPrice: {
      required: '金额不能为空'
    },
    snNum: {
      required: '设备SN号不能为空'
    },
    invoiceNum: {
      required: '发票号码不能为空'
    },
    assettypeName: {
      required: '资产类别不能为空'
    },
    address: {
      required: '资产地址不能为空'
    }
  };
}
